<template>
	<div id="admin-cptt-add">
		<Title>添加比赛</Title>
		<div id="aca-main" class="clear-both">
			<el-form ref="info" :model="info" label-width="80px">
        <div class="flex">
          <div class="flex-1 w-0 flex items-center justify-center">
            <el-upload
              v-show="!info.file"
              action="#"
              ref="cptimg"
              list-type="picture-card"
              :auto-upload="false"
              :on-change="filechange"
              :limit="1"
              :multiple="false"
              :show-file-list="false"
              >
                <i slot="default" class="el-icon-plus" />
            </el-upload>
            <div v-if="info.file" class="file-png" style="height: 280px;width: 280px;">
              <img :src="info.file.url" style="height: 100%;" class="w-full object-cover" />
              <span class="file-dark">
                <span class="file-icon icon rounded shake-little icon-ok p-2 cursor-pointer" 
                @click="clearfile" >
                  <i class="el-icon-delete"></i>
                </span>
              </span>
            </div>
            <!-- <el-upload>1111111111</el-upload>
            <img src="https://api.r10086.com/img-api.php?type=进击的巨人1" /> -->
          </div>
          <div class="flex-1 w-0">
            <el-form-item label="比赛名称" prop="name" :rules="[ { required: true, message: '请输入比赛名称', trigger: 'blur' }, { max: 8, message: '名字过长', trigger: 'blur' } ]" >
              <el-input v-model="info.name" placeholder="比赛名称" />
            </el-form-item>
            <el-form-item label="是否展示" class="is-required" >
              <el-switch
                v-model="info.isShow"
                active-text="展示"
                inactive-text="隐藏">
              </el-switch>
            </el-form-item>
            <el-form-item label="开设形式" prop="type" :rules="{ required: true, message: '请至少选择一种比赛模式', trigger: 'blur' }" >
              <el-select v-model="info.type" placeholder="开设比赛形式">
                <el-option v-for="(value,key) in CodeToType" :label="value+'赛'" :value="key" />
              </el-select>
            </el-form-item>
            <el-form-item label="报名截止" prop="overtime" :rules="OverTimeRule" class="is-required" >
              <el-date-picker v-model="info.overtime" type="datetime" placeholder="报名截止时间" align="right" :picker-options="pickerOptions" />
            </el-form-item>
            <el-form-item label="比赛开始" prop="goingtime" :rules="GoingTimeRule" class="is-required" >
              <el-date-picker v-model="info.goingtime" type="datetime" placeholder="比赛开始时间" align="right" :picker-options="pickerOptions" />
            </el-form-item>
          </div>
        </div>
        <el-form-item label="活动简介" prop="info" :rules="{ required: true, message: '请添加活动说明', trigger: 'blur' }" >
          <el-input type="textarea" maxlength="300" v-model="info.info" show-word-limit rows="6" />
        </el-form-item>
        <el-form-item label="报名要求" prop="requirements" :rules="{ required: true, message: '请添加报名要求', trigger: 'blur' }" >
          <el-input type="textarea" maxlength="300" v-model="info.requirements" show-word-limit rows="6" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">立即创建</el-button>
        </el-form-item>
			</el-form>
		</div>
	</div>
</template>
// 
<script>
import { addcptt } from '@/api/htcp'
import { CodeToType } from '@/conf'
import { blobToBase64,exportFile } from '@/utils/functions'
import { dateFormat } from '@/utils/functions'
export default{
	data(){
		const OverTimeRule = (rule,value,callback)=>{
			if(value === "")
				callback(new Error('请选择截止报名时间'))
			else if(new Date() >= value)
				callback(new Error('请选择正确的报名截止时间'));
			callback();
		};
		const GoingTimeRule = (rule,value,callback)=>{
			if(value === "")
				callback(new Error('请选择比赛开始时间'))
			else 
				if(this.info.overtime)
					{if(this.info.overtime> value)
						callback(new Error('开赛时间早于报名截止时间'));
					}
				else
					callback(new Error('请先选择报名截止时间'));
			callback();
		};
		return{
			info:{
				name:"",
				url:"https://img01.yzcdn.cn/vant/logo.png",
				overtime:"",
				goingtime:"",
				info:"",
        file:"",
				type:"",
				requirements:"",
        isShow:true
			},
      clearfile:()=>{
        this.$refs.cptimg.clearFiles()//return false
        this.info.file = false
      },
      filechange:(file,filelist)=>{
        const { url,raw } = file
        const { type:filetype,size:filesize } = raw
        const typeok = ['image/jpeg','image/png'].includes(filetype)
        const size = 5
        const sizeok = filesize / 1024 / 1024 < size
        if (!typeok) this.$message.error('文件类型异常')
        if (!sizeok) this.$message.error(`文件过大(${size}MB以内)`)
        if(!typeok || !sizeok) {
          this.clearfile()
          return
        }
        this.info.file = { url,raw }
        console.log({file,filelist})
      },
			pickerOptions:{
				shortcuts: [{
					text: '明天',
					onClick(picker) {
						const date = new Date();
						date.setTime(date.getTime() + 60*60*24*1000)
						picker.$emit('pick', date);
					}
				}, {
					text: '后天',
					onClick(picker) {
						const date = new Date();
						date.setTime(date.getTime() + 60*60*24*1000*2);
						picker.$emit('pick', date);
					}
				}, {
					text: '一周后',
					onClick(picker) {
					const date = new Date();
					date.setTime(date.getTime() + 60*60*24*1000*7);
						picker.$emit('pick', date);
					}
				}]
			},
			OverTimeRule:{
				validator:OverTimeRule,
				trigger:'blur'
			},
			GoingTimeRule:{
				validator:GoingTimeRule,
				trigger:'blur'
			},
			CodeToType:Object.freeze(CodeToType)
		}
	},
	methods:{
		async onSubmit(){
      // reader.onerror = error => reject(error)
			this.$confirm('确认要创建该比赛嘛?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
			}).then(() => {
			this.$refs["info"].validate(async (valid) => {
			if (valid){
        const { name,overtime,goingtime,info,type,requirements,isShow,file } = this.info
        const url = await blobToBase64(file.raw)
        
        console.log({ name,url,overtime,goingtime,info,type,requirements,isShow })
        await addcptt({
          name,url,
          overtime:dateFormat('YYYY-MM-DD hh:mm:ss',overtime),
          goingtime:dateFormat('YYYY-MM-DD hh:mm:ss',goingtime),
          info,type,requirements,isShow
        })
        this.$message.success("添加成功")
				// for (let a of this.info.type)
				// {
				// 	axios.post('./api/AddCptt',
				// 		{
				// 			data:{
				// 				name:this.info.name,
				// 				type:a,
				// 				url:this.info.url,
				// 				overtime:this.info.overtime.getTime(),
				// 				goingtime:this.info.goingtime.getTime(),
				// 				info:this.info.info,
				// 				requirements:this.info.requirements
				// 			},
				// 		}
				// 	).then(info=>{
				// 			this.$message({
				// 				message:info.data.info ,
				// 				type: info.data.type,
				// 				duration:info.data.type=="warning"? 0:3000,
				// 				showClose:true
				// 			});
				// 	}).catch(error=>{
				// 		console.log(error)
				// 		this.$message({ message: '服务器异常',type: 'warning'});
				// 	})
				// }
			}else{
				//表单校验失败
			}
			})
			})
		}
	}
}
</script>

<style lang="scss" scoped="scoped">
#admin-cptt-add{
	.el-select,.el-date-editor{
		width: 100% !important;
	}
}

.file-png{
  position: relative;
  &:hover .file-dark{
    opacity: 1;
  }
  .file-dark{
    position: absolute;
    width: 100%;
    height: 100%;
    left: 0;
    top: 0;
    cursor: default;
    text-align: center;
    color: #fff;
    opacity: 0;
    font-size: 20px;
    background-color: rgba(0,0,0,.5);
    transition: opacity .3s;
    display: flex;
  }
  .file-icon{
    margin: auto;
  }
}
</style>
